<a-modal
  id="prompt-modal"
  v-model="promptModal.visible"
  :title="promptModal.title"
  :closable="true"
  @ok="promptModal.ok"
  :mask-closable="false"
  :ok-text="promptModal.okText"
  cancel-text="{{ _('cancel') }}"
  v-cloak
>
  <template v-if="promptModal.type === 'bool'">
    <a-select v-model="promptModal.value" @change="handleChange" style="width: 100%">
      <a-select-option value="true">True</a-select-option>
      <a-select-option value="false">False</a-select-option>
    </a-select>
  </template>
  <template v-else>
    <a-input
      id="prompt-modal-input"
      :type="promptModal.type"
      v-model="promptModal.value"
      :autosize="{minRows: 10, maxRows: 20}"
      @keydown.enter.native="promptModal.keyEnter"
      @keydown.ctrl.83="promptModal.ctrlS"
    ></a-input>
  </template>
</a-modal>

<script>
  const promptModal = {
    title: "",
    type: "",
    value: "",
    okText: "",
    visible: false,
    confirm(){},
    keyEnter(e) {
      if (this.type !== "textarea") {
        e.preventDefault();
        this.ok();
      }
    },
    ctrlS(e) {
      if (this.type === "textarea") {
        e.preventDefault();
        promptModal.confirm(promptModal.value);
      }
    },
    ok() {
      promptModal.close();
      promptModal.confirm(promptModal.value);
    },
    open({ 
      title = "", 
      type = "text", 
      value = "", 
      okText = "{{ _('confirm') }}", 
      confirm = () => {} 
    }) {
      this.title = title;
      this.type = type;
      this.value = value;
      this.okText = okText;
      this.confirm = confirm;
      this.visible = true;
      promptModalApp.$nextTick(() => {
        if (document.querySelector("#prompt-modal-input")) {
          document.querySelector("#prompt-modal-input").focus();
        }
      });
    },
    close() {
      this.visible = false;
    },
  };

  const promptModalApp = new Vue({
    el: "#prompt-modal",
    data: {
      promptModal: promptModal,
    },
    methods: {
      handleChange(val) {
        promptModal.value = val;
      },
    },
  });
</script>
